<template>
  <view class="container">
    <button class="back-button" @click="goBack">返回</button>
    <h2 style="text-align: center">面试分析</h2>

    <!-- 思考过程显示区域 -->
    <view class="response-section">
      <h3>分析过程:</h3>
      <p>{{ reasoningContent }}</p>
    </view>

    <!-- AI 回答显示区域 -->
    <view class="response-section">
      <h3>AI 总结:</h3>
      <view class="formatted-content">
        <template v-for="(item, index) in formatContent(aiResponse)" :key="index">
          <!-- 标题 -->
          <h4 v-if="item.type === 'title'" class="title-text">{{ item.content }}</h4>

          <!-- 普通文本 -->
          <text v-else-if="item.type === 'text'">{{ item.content }}</text>

          <!-- 加粗文本 -->
          <text v-else-if="item.type === 'bold'" class="bold-text">{{
            item.content
          }}</text>

          <!-- 换行处理 -->
          <br v-if="item.content.includes('\n')" />
        </template>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted } from "vue";
import { useRoute } from "vue-router"; // 添加这行导入

// 内容格式化函数（新逻辑）
const formatContent = (content) => {
  if (!content) return [];

  const result = [];
  let currentIndex = 0;

  // 处理标题格式：### 标题
  const titleRegex = /(###\s+[^\n]+)(\n|$)/g;
  let titleMatch;

  while ((titleMatch = titleRegex.exec(content)) !== null) {
    // 添加标题前的普通文本
    if (titleMatch.index > currentIndex) {
      const textContent = content.substring(currentIndex, titleMatch.index);
      result.push(...processTextWithBold(textContent));
    }

    // 添加标题（去除###前缀）
    const title = titleMatch[1].replace(/^###\s+/, "");
    result.push({
      type: "title",
      content: title,
    });

    currentIndex = titleMatch.index + titleMatch[0].length;
  }

  // 添加剩余文本
  if (currentIndex < content.length) {
    const remainingText = content.substring(currentIndex);
    result.push(...processTextWithBold(remainingText));
  }

  return result;
};

// 处理普通文本中的加粗格式：**加粗文本**
const processTextWithBold = (text) => {
  const result = [];
  let lastIndex = 0;
  const boldRegex = /\*\*([^*]+)\*\*/g;
  let boldMatch;

  while ((boldMatch = boldRegex.exec(text)) !== null) {
    // 添加加粗前的普通文本
    if (boldMatch.index > lastIndex) {
      result.push({
        type: "text",
        content: text.substring(lastIndex, boldMatch.index),
      });
    }

    // 添加加粗文本
    result.push({
      type: "bold",
      content: boldMatch[1],
    });

    lastIndex = boldMatch.index + boldMatch[0].length;
  }

  // 添加剩余文本
  if (lastIndex < text.length) {
    result.push({
      type: "text",
      content: text.substring(lastIndex),
    });
  }

  return result;
};

// 从页面参数获取interview_id和fileids
const route = useRoute();
const interviewId = ref(route.query.interview_id || "");
const field = ref(route.query.fileids || "");

// WebSocket 连接实例
const ws = ref(null);
const wsConnected = ref(false);
const sending = ref(false);

const goBack = () => {
  uni.reLaunch({
    url: '/pages/index/find',
  });
};

// 响应式数据：AI回答和思考内容
const aiResponse = ref("");
const reasoningContent = ref("");
const token = uni.getStorageSync("access_token") || "";
// 新增 WebSocket 连接方法
const connectChatWebSocket = () => {
  return uni.connectSocket({
    url: "ws://localhost:8086/overview",
    complete: () => {},
  });
};

// 页面加载时建立 WebSocket 连接
onMounted(() => {
  ws.value = connectChatWebSocket();

  // 监听连接打开事件
  ws.value.onOpen(() => {
    console.log("WebSocket 已连接");
    wsConnected.value = true;
    uni.showToast({ title: "已连接到 WebSocket" });

    ws.value.send({
      data: token,
      fail: (err) => console.error("TOKEN失败:", err),
    });

    // 连接建立后立即发送业务数据
    const message = {
      interviewId: interviewId.value,
      field: field.value,
    };
    ws.value.send({
      data: JSON.stringify(message),
      fail: (err) => console.error("发送业务数据失败:", err),
    });
  }); // 这里闭合 onOpen 回调

  // 监听消息接收（确保在 onMounted 内部）
  ws.value.onMessage((res) => {
    try {
      const data = JSON.parse(res.data);
      // console.log("RES", res); // 现在应该会执行
      // console.log("DATA", data);

      if (data.contentTotal !== undefined) {
        aiResponse.value = data.contentTotal;
        // console.log("AiRespons", aiResponse.value);
      }

      if (data.reasingContentTotal !== undefined) {
        reasoningContent.value = data.reasingContentTotal;
      }
    } catch (e) {
      console.error("解析消息失败:", e);
    }
  });

  // 监听连接关闭
  ws.value.onClose(() => {
    console.log("WebSocket 已关闭");
    wsConnected.value = false;
  });

  // 监听错误
  ws.value.onError((err) => {
    console.error("WebSocket 错误:", err);
    uni.showToast({ title: "WebSocket 错误", icon: "none" });
  });
});
</script>

<style scoped>
.container {
  max-width: 600px;
  margin: 2rem auto;
  padding: 2rem;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}

.input-group {
  margin-bottom: 1.5rem;
}

label {
  display: block;
  margin-bottom: 0.5rem;
}

input {
  width: 100%;
  padding: 0.5rem;
  border: 1px solid #ddd;
  border-radius: 4px;
}

button {
  width: 100%;
  padding: 0.75rem;
  background-color: #28a745;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  margin-bottom: 1rem;
}

button:disabled {
  background-color: #6c757d;
  cursor: not-allowed;
}

.response-section {
  margin-top: 1.5rem;
  padding: 1rem;
  background-color: #f9f9f9;
  border: 1px solid #eee;
  border-radius: 4px;
}

.info-section {
  margin-bottom: 20px;
  padding: 15px;
  background-color: #f5f7fa;
  border-radius: 8px;
  border: 1px solid #ebeef5;
}

.formatted-content {
  white-space: pre-wrap; /* 保留换行符 */
}

.bold-text {
  font-weight: bold;
}

/* 响应式区域样式调整 */
.response-section {
  margin-top: 1.5rem;
  padding: 1rem;
  background-color: #f9f9f9;
  border: 1px solid #eee;
  border-radius: 4px;
}
</style>
